import 'es6-promise'
import axios from 'axios';
import {message, notification} from 'antd';
import { store } from '@/store'
import { HashRouter ,useHistory } from 'react-router-dom'
// import {logout} from '@/components/common/header'
let pathname = '';
const service = axios.create({
    timeout: 600000
});

const router: CommonObjectType = new HashRouter({})
const CancelToken = axios.CancelToken;
let source = CancelToken.source();
let isUnauthorized = false;
service.interceptors.request.use(config => {
    let paramsToken = config.params?config.params.token:'';
    config.cancelToken = source.token;
    const { token = paramsToken } = store.getState().storeData.userInfo || {}
    if(process.env.NODE_ENV!=='development'){
        config.url = pathname+config.url;
    }else{
        config.url = config.url;
    }
    // config.data['token'] = token;
    config.withCredentials = true;
    config.headers['Content-Type']='application/json; charset=utf-8';
    config.headers['Accept']='*/*';
    config.headers.token = token
    config.headers.authorization = token
    
    // 对get/delete参数进行编码处理
    // if ((config.method.toLowerCase() === 'get' || config.method.toLowerCase() === 'delete')&&config.params) {
    //     const keys = Object.keys(config.params)
    //     config.url = keys.reduce((pre, cur) => `${pre}${cur}=${config.params[cur]}&`, config.url + '?')
    //     config.url = encodeURI(config.url.substr(0, config.url.length - 1))
    // }
    if(config.data&&config.data.isFormData){
        config.headers['Content-Type']='multipart/form-data';
    }
    return config
}, error => {
    return Promise.reject(error)
});

service.interceptors.response.use(response => {
   
    if(response.headers['content-disposition']){
        convertRes2Blob(response);
        return;
    }
    if (response.status >= 200 && response.status < 300) {
        switch (response.data.code) {
            case '-1':
            case '-2':
            case '-1000':
            case '-3002':
            case '-3003':
            case '-2012':
            case '7053':
            case '-3001':
            case '-2016':
            case '1022':
            case '-1021':
                message.error(response.data.message);
                return Promise.reject({});
            default:
                return Promise.resolve({
                    ...response.data,
                    ...{
                        authorization: response.headers.authorization
                    }
                });
        }
    }else{
      
    }
    const codeMessage = {
        200: '服务器成功返回请求的数据。',
        201: '新建或修改数据成功。',
        202: '一个请求已经进入后台排队（异步任务）。',
        204: '删除数据成功。',
        400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
        401: '用户没有权限（令牌、用户名、密码错误）。',
        403: '用户得到授权，但是访问是被禁止的。',
        404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
        406: '请求的格式不可得。',
        410: '请求的资源被永久删除，且不会再得到的。',
        422: '当创建一个对象时，发生一个验证错误。',
        500: '服务器发生错误，请检查服务器。',
        502: '网关错误。',
        503: '服务不可用，服务器暂时过载或维护。',
        504: '网关超时。',
    };

    notification.open({
        message: response.status,
        description: codeMessage[response.status],
        onClick: () => {
            console.log('Notification Clicked!');
        },
    });
    
    const error = new Error(response.statusText);
   
    // error.response = response;
    return Promise.reject(error)
}, error => {
    // if (error.response.data.code === 2002) {
    //     window.location.href = window.location.origin + '/#/user/login';
    // }
    const codeMessage = {
        200: '服务器成功返回请求的数据。',
        201: '新建或修改数据成功。',
        202: '一个请求已经进入后台排队（异步任务）。',
        204: '删除数据成功。',
        400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
        401: '用户没有权限（令牌、用户名、密码错误）。',
        403: '用户得到授权，但是访问是被禁止的。',
        404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
        406: '请求的格式不可得。',
        410: '请求的资源被永久删除，且不会再得到的。',
        422: '当创建一个对象时，发生一个验证错误。',
        500: '服务器发生错误，请检查服务器。',
        502: '网关错误。',
        503: '服务不可用，服务器暂时过载或维护。',
        504: '网关超时。',
    };

   
    if(error.response.status==401){
        if(!isUnauthorized){
            isUnauthorized = true;
            notification.open({
                message: error.response.status,
                description: codeMessage[error.response.status],
                onClick: () => {
                    console.log('Notification Clicked!');
                },
            });
            window['logouFn']();
            setTimeout(() => {
                isUnauthorized = false;
            }, 1000);
        }
       
    }else{
        notification.open({
            message: error.response.status,
            description: codeMessage[error.response.status],
            onClick: () => {
                console.log('Notification Clicked!');
            },
        });
    }
    
    return Promise.reject(error)
});
const requestion= (config={}) =>{
    return service(config)
}


const Get = (url: string, params?: object): Promise<any> =>{
   return requestion({
        url: url,
        method: 'get',
        params: params
    })
}
const Download = (url: string, data?: object): Promise<any> =>{
    let params = {
        url: url,
        method: 'post',
        data: data,
        responseType:'blob',
    }
   
    return requestion(params)
};


const Post = (url: string, data?: object): Promise<any> =>{
    return requestion({
        url: url,
        method: 'post',
        data: data
    })
} 
const Delete = (url: string, data?: object,isBody?:false): Promise<any> =>{
    let params = {
        url: url,
        method: 'delete',
    }
    if(data&&data['isBody']){
        params['data'] = data;
    }else{
        params['params'] = data;
    }
    return requestion(params)
}
const Put = (url: string, data?: object): Promise<any> =>{
    return requestion({
        url: url,
        method: 'put',
        data: data
    })
}
const  FormDataSubmit = (url: string, data?: object): Promise<any> =>{
    return requestion({
        url: url,
        method: 'post',
        data: {
            ...data,
            ...{
                isFormData:true
            }
        }
    })
}

export function All(optionArr:any) {
    return axios.all(optionArr)
        .then(axios.spread(function (acct, perms) {
            // 两个请求现在都执行完成
        }));
}
// token失效，清除用户信息并返回登录界面
const clearAll = () => {
    store.dispatch({
        type: 'SET_USERINFO',
        payload: {}
    })
    router.history.replace({ pathname: '/login' })
}



export {
    pathname,
    clearAll,
    Download,
    FormDataSubmit
} 

service.get = Get;
service.post = Post;
service.delete = Delete;
service.put = Put;

export default service;
function convertRes2Blob(response:any) {
    console.log(123);
    // 提取文件名
    let fileName = response.headers['content-disposition'].match(
      /filename=(.*)/
    )[1]
    fileName = decodeURI(fileName)

    const type = response.headers['content-type'];
    console.log(type)
    // 将二进制流转为blob
    const blob = new Blob([response.data], { type: 'type' })
    
    if ('msSaveOrOpenBlob' in navigator) {
         
          window.navigator.msSaveOrOpenBlob(blob, fileName);
        } else {
          
          var url = window.URL.createObjectURL(blob);
          var link = document.createElement('a');
          
          link.style.display = 'none';
          link.href = url;
          link.setAttribute('download', fileName);
          link.setAttribute('id', 'downLoadFile');
          console.log(link);
          window.document.body.appendChild(link);
         
          link.click();
    
        }
  }